package com.zhang.productcenter.service;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.CountDownLatch;

/**
 * <p>
 * 商品款式基础表 服务实现类
 * </p>
 *
 * @author KingHood
 * @since 2023-12-20
 */
@RequiredArgsConstructor
@Slf4j
@Transactional(rollbackFor = Exception.class)
@Service
public class ProductBaseServiceImpl implements IProductBaseService {


    @Override
    public List<Map<String, Object>> importProduct(MultipartFile file) {
        try {
            CountDownLatch latch = new CountDownLatch(1);

            String fileName = file.getOriginalFilename();
            String finalFileName = fileName + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
            log.info("文件名：{}", fileName);
            EasyExcel.read(file.getInputStream(), new AnalysisEventListener<Map<Integer, String>>() {
                private static final int BATCH_COUNT = 100;
                private List<Map<Integer, String>> cachedDataList = new ArrayList<>(BATCH_COUNT + 20);
                private String last;
                private Map<Integer, String> head;
                private Map<String, Integer> fieldMap;

                @Override
                public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
                    log.info("头行数据：{}", headMap);
                    head = headMap;
                    fieldMap = new HashMap<>(headMap.size());
                    headMap.forEach((x, y) -> {
                        fieldMap.put(y, x);
                    });
                }

                @Override
                public void invoke(Map<Integer, String> data, AnalysisContext context) {
                    ReadRowHolder readRowHolder = context.readRowHolder();
                    Integer rowIndex = readRowHolder.getRowIndex();
                    log.info("第{}行数据:{}", rowIndex, data);

                    Integer styleNumberIndex = fieldMap.get("款号");
                    String styleNumber = data.get(styleNumberIndex);
                    if (cachedDataList.size() >= BATCH_COUNT && !Objects.equals(last, styleNumber)) {
                        // 保存到redis
                        saveExcelData(cachedDataList, fieldMap, finalFileName);
                        cachedDataList = new ArrayList<>(BATCH_COUNT + 20);
                    }
                    last = styleNumber;
                    cachedDataList.add(data);
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext context) {
                    saveExcelData(cachedDataList, fieldMap, finalFileName);
                    log.info("excel数据读取结束");
                    latch.countDown();
                }

            }).sheet().doRead();

            latch.await();

        } catch (Exception e) {
            log.error("excel文件读取失败：", e);
        }

        return null;
    }

    private void saveExcelData(List<Map<Integer, String>> list, Map<String, Integer> fieldMap, String fileName) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        log.info("导入商品：fileName：{}，list：{}，fieldMap：{}", fileName, list, fieldMap);

    }

    @Override
    public void downLoad(List<Map<String, Object>> list, HttpServletResponse response) {

    }
}
